package com.qb.hotelTV.network;

import android.util.Log;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 重试拦截器
 * 处理网络请求失败时的自动重试逻辑
 */
public class RetryInterceptor implements Interceptor {
    private static final String TAG = "RetryInterceptor";
    
    private int maxRetryCount;
    private long retryDelayMillis;
    
    public RetryInterceptor(int maxRetryCount) {
        this(maxRetryCount, 1000); // 默认延迟1秒
    }
    
    public RetryInterceptor(int maxRetryCount, long retryDelayMillis) {
        this.maxRetryCount = maxRetryCount;
        this.retryDelayMillis = retryDelayMillis;
    }
    
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = null;
        IOException lastException = null;
        
        for (int retryCount = 0; retryCount <= maxRetryCount; retryCount++) {
            try {
                if (retryCount > 0) {
                    Log.d(TAG, "重试请求 " + retryCount + "/" + maxRetryCount + ": " + request.url());
                    
                    // 延迟重试
                    try {
                        Thread.sleep(retryDelayMillis * retryCount); // 递增延迟
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        throw new IOException("重试被中断", e);
                    }
                }
                
                response = chain.proceed(request);
                
                // 检查响应是否成功
                if (response.isSuccessful()) {
                    if (retryCount > 0) {
                        Log.d(TAG, "重试成功: " + request.url());
                    }
                    return response;
                } else {
                    Log.w(TAG, "响应失败 " + response.code() + ": " + request.url());
                    
                    // 对于某些状态码不进行重试
                    if (!shouldRetry(response.code())) {
                        Log.d(TAG, "状态码 " + response.code() + " 不进行重试");
                        return response;
                    }
                    
                    // 关闭响应体以释放连接
                    if (response.body() != null) {
                        response.body().close();
                    }
                }
                
            } catch (IOException e) {
                lastException = e;
                Log.w(TAG, "请求失败 " + (retryCount + 1) + "/" + (maxRetryCount + 1) + ": " + e.getMessage());
                
                // 最后一次重试失败，抛出异常
                if (retryCount == maxRetryCount) {
                    throw e;
                }
            }
        }
        
        // 如果所有重试都失败了，抛出最后一个异常
        if (lastException != null) {
            throw lastException;
        }
        
        // 理论上不应该到达这里
        return response;
    }
    
    /**
     * 判断是否应该重试
     * @param responseCode HTTP响应码
     * @return 是否应该重试
     */
    private boolean shouldRetry(int responseCode) {
        // 4xx 客户端错误通常不应该重试（除了408、429）
        // 5xx 服务器错误可以重试
        switch (responseCode) {
            case 400: // Bad Request
            case 401: // Unauthorized
            case 403: // Forbidden
            case 404: // Not Found
            case 405: // Method Not Allowed
            case 406: // Not Acceptable
            case 409: // Conflict
            case 410: // Gone
            case 422: // Unprocessable Entity
                return false;
                
            case 408: // Request Timeout
            case 429: // Too Many Requests
            case 500: // Internal Server Error
            case 502: // Bad Gateway
            case 503: // Service Unavailable
            case 504: // Gateway Timeout
                return true;
                
            default:
                // 其他5xx错误也重试
                return responseCode >= 500;
        }
    }
} 